# -*- coding: UTF-8 -*- 
from BeautifulSoup import BeautifulSoup
import urllib2
from deal_info_web import *

def deal_city(tuan, city):
    (f_id, d_id, orig) = judge_begin(tuan, city)

    f_url = urllib2.urlopen('http://tuan.qq.com/%s/' % (city))

    soup = BeautifulSoup(f_url.read())

    f_xml = open('%sxml/%s_%s.xml' % (get_home_dir(), tuan, city), 'w')
    
    f_xml.write('<deals>\n')
    
    deal_id = soup.find(attrs={'class':'current_price'}).button['onclick'].replace('location.href="/shenzhen/deal/buy/', '').replace('"', '')
    if not judge(f_id, d_id, deal_id):
	f_xml.write('\t' + '<deal>\n')
	deal_info_source(f_xml, 'QQ', 'QQ团购'.decode('utf-8'), 'http://tuan.qq.com/', 'http://tuan.qq.com/')

	f_xml.write('\t' * 2 + '<city>%s</city>\n' % city)

	deal_info_add(f_xml, 'id', deal_id, 2)
	deal_title = soup.find(attrs={'class':'tit'}).h3.contents[2].replace('\t', '').replace('\n', '')
	deal_info_add(f_xml, 'name', deal_title, 2)
	deal_info_cats(f_xml, deal_title)
	deal_vendor_name = soup.find(attrs={'class':'shop_address'}).h4.contents[0]
	deal_info_vendor(f_xml, deal_vendor_name)
	deal_info_time(f_xml)
	deal_value = soup.find(attrs={'class':'primary_price'}).contents[1].contents[0].replace('&yen;','')
	deal_info_add(f_xml, 'o_price', deal_value, 2)
	deal_price = soup.find(attrs={'class':'current_price'}).span.contents[0].replace('&yen;', '')
	deal_info_add(f_xml, 'c_price', deal_price, 2)
	deal_info_discount_and_save_money(f_xml, deal_price, deal_value)
	deal_img = soup.find(attrs={'class':'photo'}).img['src']
	deal_info_img(f_xml, deal_img)
	deal_url = 'http://tuan.qq.com/shenzhen/deal/show/%s' % (deal_id)
	deal_info_add(f_xml, 'url', deal_url, 2)

	f_xml.write('\t' + '</deal>\n')

    f_xml.write(orig[8 : ])

    f_xml.close()
    f_id.close()

    judge_end(tuan, city)



deal_city('qq', 'shenzhen')
